const express = require('express');
const axios = require('axios');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('../frontend'));

// 获取草料二维码图片
app.get('/qr', async (req, res) => {
    const { url, mhid = 'sELAVNMfK8k' } = req.query;

    if (!url) {
        return res.status(400).json({ 
            error: '缺少必要参数：url' 
        });
    }

    try {
        // 草料二维码API
        const apiUrl = `https://api.cl2wm.cn/api/qrcode/code?text=${encodeURIComponent(url)}&mhid=${mhid}`;
        
        // 获取二维码页面
        const response = await axios.get(apiUrl, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
        });

        const html = response.data;
        
        // 从HTML中提取图片URL
        const imgMatch = html.match(/img src="([^"]+)"/);
        if (imgMatch && imgMatch[1]) {
            const imgUrl = imgMatch[1].startsWith('http') ? imgMatch[1] : `https:${imgMatch[1]}`;
            res.json({ 
                success: true,
                url: imgUrl,
                originalUrl: url,
                templateId: mhid
            });
        } else {
            res.status(500).json({ 
                error: '无法从响应中提取二维码图片' 
            });
        }

    } catch (error) {
        console.error('获取二维码失败:', error.message);
        res.status(500).json({ 
            error: '获取二维码失败，请稍后重试',
            details: error.message
        });
    }
});

// 健康检查
app.get('/health', (req, res) => {
    res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`草料二维码服务运行在 http://localhost:${PORT}`);
    console.log(`访问 http://localhost:${PORT} 查看前端页面`);
});
